import re
import random
import time
import json
import datetime as dt

import requests
import redis
from urllib.parse import quote, unquote
import decrypt
from pyquery import PyQuery

from loguru import logger

redis_cli = redis.Redis()


# uid = '37754235'
# uid = '38510798'
# uid = '38510755'
# uid = [f'385106{i}' for i in range(10, 60)]


# print(unquote(unquote('%257B%2522uid%2522%253A%252238510798%2522%252C%2522token%2522%253A%2522%2522%257D')))

# exit('')

def start(listid, uid, session, proxies=None):
    cookies = {
        'D5O_openinfos': quote(quote(f'{{"uid":"{uid}","token":""}}')),
    }

    headers = {
        'Host': 'h5.zhiyyuan.cn',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/7.0.15(0x17000f2b) NetType/WIFI Language/zh_CN',
        'Accept-Language': 'zh-cn',
        'Refer': 'https://h5.zhiyyuan.cn/m.php?v=0cf703fcd4add7d4&id=115&sign=friend&from=groupmessage&id=70&sign=friend&id=107&sign=friend',
    }

    response = session.get(
        'https://h5.zhiyyuan.cn/m.php?v=0cf703fcd4add7d4&id=115&sign=friend&from=groupmessage&id=70&sign=friend&id=107&sign=friend',
        headers=headers,
        cookies=cookies,
        proxies=proxies,
        timeout=10)

    html = response.text
    # print(html)
    # print(response.ok)
    tokenVal = re.findall("tokenVal='(.*?)'", html)
    print(tokenVal)
    exit(2)
    if not tokenVal:
        raise requests.exceptions.ProxyError
    if tokenVal[0] == '':
        return
    if dt.datetime.now().minute == 00 or dt.datetime.now().minute == 30:
        if redis_cli.sadd('vote_time', dt.datetime.now().strftime('%Y-%m-%d %H:%M:00')):
            doc = PyQuery(html)
            redis_cli.hset('votes_hd', f'{dt.datetime.now()}', f'{doc(".x_4397421").text()}')
            redis_cli.hset('votes_hy', f'{dt.datetime.now()}', f'{doc(".x_4396924").text()}')
            redis_cli.hset('votes_sg', f'{dt.datetime.now()}', f'{doc(".x_4735510").text()}')

    ouidVal = re.findall("ouidVal='(.*?)'", html)
    while 1:
        brandid = '1902857'
        idnum = brandid + listid
        zheng = ''
        idlength = 20 - len(idnum)

        for _ in range(idlength):
            zheng += str(round(random.random() * 9))

        rnd = f'{brandid}{listid}{zheng}'

        captcha_url = f'https://v.tiantianvote.com/api/c2/captchas.png.php?rnd={rnd}&type=2&id={listid}'

        # time.sleep(1)
        resp = session.get(captcha_url, proxies=proxies, timeout=10)
        # print(resp.ok)
        with open('vote.jpg', 'wb') as f:
            f.write(resp.content)
        pic_str = captcha_crack(resp.content, 1902)

        # captcha = input('输入验证码')

        captcha = (decrypt.decrypt(pic_str)).strip()

        data = {
            'captcha': captcha,
            'rnd': rnd,
            'type': 2,
            'id': listid,
        }
        time.sleep(1)
        resp = session.post('https://v.tiantianvote.com/api/c2/captchas.check1.php', data=data, proxies=proxies,
                            timeout=10)
        print(resp.text)
        if re.search('﻿{"status":200,', resp.text):
            # print(captcha)
            break
        else:
            # time.sleep(random.randint(10, 60) * random.random())
            continue

    # print(captcha)
    data = {
        'brandid': brandid,
        'itemid': listid,
        'yqm': captcha,
        'rnd': rnd,
        'token': tokenVal[0],
        'ouid': uid,
        'sid': '0cf703fcd4add7d4',
    }
    time.sleep(1)

    headers_p = {
        'Host': 'v.tiantianvote.com',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Origin': 'https://h5.zhiyyuan.cn',
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/7.0.15(0x17000f2b) NetType/WIFI Language/zh_CN',
        'Referer': 'https://h5.zhiyyuan.cn/m.php?v=0cf703fcd4add7d4&id=115&sign=friend&from=groupmessage&id=70&sign=friend&id=107&sign=friend',
        'Accept-Language': 'zh-cn',
    }

    resp = requests.post('https://v.tiantianvote.com/v.php', data=data, headers=headers_p, proxies=proxies, timeout=10)
    print(resp.text)
    if re.search('"code":1,"msg":"success"', resp.text):
        redis_cli.sadd('success_uid', uid)
        redis_cli.set(uid, 1, ex=1800)

    if re.search('{"code":11,"msg"', resp.text):
        ...
        # redis_cli.srem('success_uid', uid)
    if re.search('{"code":6,"msg"', resp.text):
        raise requests.exceptions.ProxyError
    raise requests.exceptions.ProxyError


def captcha_crack(content, code_type):
    # data = {
    #     'user': 'dacai001',
    #     'pass': '136409304Xx',
    #     'softid': '906693',
    #     'codetype': code_type,
    # }
    #
    # files = {'userfile': ('captcha.jpg', content)}
    # response = requests.post(
    #     'http://upload.chaojiying.net/Upload/Processing.php',
    #     data=data,
    #     files=files,
    #     headers={'Connection': 'Keep-Alive',
    #              'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)'},
    # )
    # results = response.json()
    # print(results)
    # if results['err_no'] == 0:
    #     time.sleep(3)
    #     return results['pic_id'], results["pic_str"]
    resp = requests.post("http://127.0.0.1:7788", data=content)
    code = resp.json()["code"]
    return code


@logger.catch
def get_proxies():
    ip_list = []
    # ip_proxy = redis_cli.get('ip_proxy')
    # if not ip_proxy:
    #     for i in range(1, 6):
    #         page = requests.get(f'https://ip.jiangxianli.com/?page={i}&country=%E4%B8%AD%E5%9B%BD').text
    #         ip_list += re.findall('<link rel="dns-prefetch" href="//(\d+\.\d+\.\d+\.\d+:\d+)">', page)
    # else:
    #     ip_list = [ip_proxy.decode().strip()]
    # proxy_use_times = redis_cli.get('proxy_use_times')
    # if proxy_use_times:
    #     proxy_use_times = proxy_use_times.decode()
    #     if proxy_use_times == '10':
    #         redis_cli.delete('proxy_use_times')

    # ip_proxy = redis_cli.get('ip_proxy')
    # if ip_proxy:
    #     ip_list = [ip_proxy.decode().strip()]
    # else:

    # if not redis_cli.exists('vote_proxies'):
    #     params = {
    #         'apikey': '9eceff6b6002ffb5defcca8d8f6b00d52f53871e',
    #         'num': 20,
    #         'type': 'json',
    #         'line': 'win',
    #         'proxy_type': 'secret'
    #     }
    #     resp = requests.get('https://www.7yip.cn/api/', params=params)
    #
    #     for ip in resp.json():
    #         redis_cli.lpush('vote_proxies',ip)
    #
    # ip = redis_cli.rpop('vote_proxies').decode()
    ip = '60.169.134.85:4236'
    # for ip in ip_list:
    #     if redis_cli.sismember('band_ip', ip):
    #         continue

    proxies = {
        'http': f'http://{ip}',
        'https': f'https://{ip}'
    }
    try:
        resp = requests.get('https://httpbin.org/get', proxies=proxies, timeout=5)
    except requests.exceptions.ProxyError:
        logger.info(f'ProxyError {ip}')
        redis_cli.delete('ip_proxy')
        return None, None
    except requests.exceptions.Timeout:
        logger.info(f'Timeout {ip}')
    except Exception as e:
        logger.info(str(e))
        return None, None
    else:
        logger.info(f'{ip} ok')
        if resp.ok:
            redis_cli.set('ip_proxy', ip)
            return proxies, ip
    return None, None


def ban_ip(redis_cli, ip):
    if ip:
        redis_cli.sadd('band_ip', ip)


def main():
    session = requests.session()

    while 1:
        _7_clock = dt.datetime.strptime(dt.datetime.now().strftime('%Y-%m-%d 07:00:00'), '%Y-%m-%d %H:%M:%S')
        _24_clock = dt.datetime.strptime(dt.datetime.now().strftime('%Y-%m-%d 23:59:59'), '%Y-%m-%d %H:%M:%S')
        now = dt.datetime.now()

        if _7_clock < dt.datetime.now() < _24_clock:  # and 0 <= now.minute <= 45
            # success_uid_list = redis_cli.smembers('success_uid')
            # for success_uid in success_uid_list:
            #
            #     start_uid = success_uid.decode()
            #     if redis_cli.exists(start_uid):
            #         time.sleep(0.01)
            #         continue
                start_uid = '37754235'
                # start_uid = '37367525'
                proxies = None
                ip = True
                # proxies, ip = get_proxies()
                # if not ip:
                #     logger.info(success_uid)
                #     continue
                logger.info(f'start uid1:{start_uid}')
                try:
                    start('4396924', str(start_uid), session, proxies)
                except requests.exceptions.ProxyError:
                    redis_cli.delete('ip_proxy')
                    ban_ip(redis_cli, ip)
                except requests.exceptions.Timeout:
                    redis_cli.delete('ip_proxy')
                    ban_ip(redis_cli, ip)
                except Exception as e:
                    logger.info(str(e))
                exit(1)

                # start_uid_2 = redis_cli.get('start_uid2').decode()
                #
                # logger.info(f'start uid2:{start_uid_2}')
                # proxies, ip = get_proxies()
                # if not ip:
                #     continue
                # try:
                #     start('4396924', str(start_uid_2), session, proxies)  # 特发
                # except requests.exceptions.ProxyError:
                #     redis_cli.delete('ip_proxy')
                #     ban_ip(redis_cli, ip)
                # except requests.exceptions.Timeout:
                #     redis_cli.delete('ip_proxy')
                #     ban_ip(redis_cli, ip)
                # except Exception as e:
                #     logger.info(str(e))
                # redis_cli.incrby('start_uid2')

        # time.sleep(1)


if __name__ == '__main__':
    main()
# cbd9e9502c3fffd6605f579480f58ce2
# cbd9e9502c3fffd6605f579480f58ce2
# cbd9e9502c3fffd6605f579480f58ce2